package com.fruits.dao.impl;

import com.fruits.domain.User;
import com.fruits.dao.UserDao;
import com.fruits.util.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class UserDapImpl implements UserDao {

    private QueryRunner queryRunner = new QueryRunner( DruidUtils.getDataSource());
    @Override
    public int add(User user) {
        String sql="insert into user(email,phone,pwd,uname) values(?,?,?,?)";
        Object[] params={user.getEmail(),user.getPhone(),user.getPwd(),user.getUname()};
        int row = 0;
        try {
            row = queryRunner.update(sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return row;
    }

    @Override
    public User findByStr(String str)  {
     String sql="SELECT * FROM user WHERE email=? OR phone=?";
     Object[] params={str,str};
        User user = null;
        try {
            user = queryRunner.query(sql, new BeanHandler<User>(User.class), params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return user;
    }

    @Override
    public List<User> findAll() {
        String sql="SELECT * FROM user";
        try {
            List<User> userList= queryRunner.query(sql, new BeanListHandler<>(User.class));
            return userList;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public User findById(int id) {
        String sql="SELECT * FROM user WHERE id=?";
       Object[] params={id};
        try {
            User user = queryRunner.query(sql, new BeanHandler<User>(User.class), params);
            return user;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int update(User user) {
        String sql="UPDATE user SET email=?,phone=?,pwd=?,uname=? WHERE id=?";
       Object[] params={user.getEmail(),user.getPhone(),user.getPwd(),user.getUname(),user.getId()};
        try {
            int update = queryRunner.update(sql, params);
            return update;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int delete(int id) {
        String sql="DELETE FROM user WHERE id=?";
        Object[] params={id};
        try {
         int row=   queryRunner.update(sql, params);
         return row;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }


}
